package com.lyy.service.impl;


import com.lyy.entity.Product;
import com.lyy.mapper.ProductMapper;
import com.lyy.service.ProductService;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Liangyaoyun
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Long updateStock(Long productId, Long number) throws TransactionException {
        // 根据主键查询商品信息
        Product product = productMapper.selectById(productId);
        if (product == null) {
            // 回滚Seata事务: reload()方法需要抛出TransactionException异常，不要捕获该异常
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            throw new RuntimeException("商品不存在");
        }

        // 判断库存是否充足
        Long currentStock = product.getStock();
        if (currentStock < number) {
            // 回滚Seata事务: reload()方法需要抛出TransactionException异常，不要捕获该异常
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            throw new RuntimeException("库存不足");
        }

        // 更新库存
        product.setStock(currentStock - number);
        return productMapper.updateStock(product);
    }

    @Override
    public Product selectById(Long productId) {
        return null;
    }

}